import axios from 'axios'
import $notify from '../utils/notify.js'

const config = {
  timeout: 60000,
  // withCredentials: true, // 跨域请求时发送cookie
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
}

const service = axios.create(config)

service.interceptors.request.use((config) => {
  console.groupCollapsed('### request:', config.url)
  console.log('method: ', config.method)
  console.log('params: ', config.params || config.data?.params || null)
  console.groupEnd()

  // 记录请求次数
  window.requestCount = window.requestCount ? window.requestCount + 1 : 1

  $notify.showLoading()
  return config
})

service.interceptors.response.use((response) => {
  console.groupCollapsed('--- response:', response.config.url)
  console.log('res: ', response.data)
  console.groupEnd()

  // 所有请求完成后关闭loading
  window.requestCount -= 1
  if (window.requestCount === 0) {
    $notify.hideLoading()
  }

  return response.data
}, (error) => {
  window.requestCount -= 1
  if (window.requestCount === 0) {
    $notify.hideLoading()
  }
  $notify.showMsg({
    type: 'error',
    text: error.message
  })
  return Promise.reject(error)
})

export default service